package com.asktgapp.user.activity;

import android.Manifest;
import android.app.Notification;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.dialog.TokenInvalidDialog;
import com.asktgapp.eventbus.EngineerPassEvent;
import com.asktgapp.eventbus.HasNewEvent;
import com.asktgapp.eventbus.PersonalCenterEvent;
import com.asktgapp.eventbus.WebEvent;
import com.asktgapp.hxsg.BiuEaseHelper;
import com.asktgapp.model.DifferentTypeVO;
import com.asktgapp.model.MipushVo;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.receiver.JGOnePixelReceiver;
import com.asktgapp.receiver.MyZhiChiMagessReceiver;
import com.asktgapp.receiver.MyZhiChiReceiver;
import com.asktgapp.user.fragment.ConsultNewFragment;
import com.asktgapp.user.fragment.NewNewHomeFragment;
import com.asktgapp.user.fragment.NewPersonalCenterFragment;
import com.asktgapp.user.fragment.PayConsultFragment;
import com.asktgapp.user.fragment.ShopWebViewFragment;
import com.asktgapp.utils.DifferentNotifications;
import com.google.gson.Gson;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.util.EMLog;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.model.Information;
import com.sobot.chat.utils.ZhiChiConstant;
import com.tencent.bugly.beta.Beta;
import com.umeng.analytics.MobclickAgent;

import org.android.agoo.common.AgooConstants;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    private RadioGroup mButtonGroup;
    private TextView title;
    private ViewPager mViewPager;
    private AppBarLayout mAppBarLayout;
    private Toolbar mToolbar;
    private myPagerAdapter mPagerAdapter;
    private long firstClickBack = 0;
    private ImageView mMessageImg, ivMyShop;
    private int flag = 0, index = 0;
    private RadioButton btn_consult, btn_center, ben_home, btnShopping;
    private ImageView HasNew;
    public TokenInvalidDialog dialog;
    public FragmentManager manager;
    JGOnePixelReceiver onePixelReceiver;
    MyZhiChiReceiver myZhiChiReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        if (MyApplication.getInstance().showSplash) {
//            Intent intent = new Intent(this, SplashActivity.class);
//            startActivity(intent);
//        }
        initView();

        MyApplication.getInstance().addActivity(this);
        EventBus.getDefault().register(this);
        dialog = new TokenInvalidDialog(null, new TokenInvalidDialog.onResultCallBack() {
            @Override
            public void onSure() {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
        manager = getSupportFragmentManager();

        onePixelReceiver = new JGOnePixelReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.SCREEN_OFF");
        intentFilter.addAction("android.intent.action.SCREEN_ON");
        intentFilter.addAction("android.intent.action.USER_PRESENT");
//        registerReceiver(onePixelReceiver, intentFilter);

        MyZhiChiReceiver myZhiChiReceiver = new MyZhiChiReceiver();//客服广播
        IntentFilter zhichi = new IntentFilter();
        zhichi.addAction(ZhiChiConstant.SOBOT_NOTIFICATION_CLICK);

        registerReceiver(myZhiChiReceiver, zhichi);
        MyZhiChiMagessReceiver magess = new MyZhiChiMagessReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ZhiChiConstant.sobot_unreadCountBrocast);
        registerReceiver(magess, filter);
        Log.e("sesss", MyApplication.mPushAgent.getRegistrationId());
        if (flag == 222) {
            if (mViewPager != null) {
                mViewPager.setCurrentItem(2);
                btn_center.setChecked(true);
            }
        }

        new Handler().postDelayed(new Runnable() {
            public void run() {
                Beta.checkUpgrade(false, false);
            }
        }, 1000);
        mipush();

    }


    private void mipush() {
        getPermissions();
        String body = getIntent().getStringExtra(AgooConstants.MESSAGE_BODY);

        if (!TextUtils.isEmpty(body)) {
            Log.i("xxxxxxxx", body);
            MipushVo mipushVo = new Gson().fromJson(body, MipushVo.class);
            if (mipushVo != null && mipushVo.getExtra() != null) {
                String ref_type = mipushVo.getExtra().getRef_type();
                String ref_id = mipushVo.getExtra().getRef_id();

                String huanxin_id = mipushVo.getExtra().getHuanxin_id();
                String cid = mipushVo.getExtra().getCid();
                String user_id = mipushVo.getExtra().getUser_id();
                String toUserName = mipushVo.getExtra().getUsername();
                String pic = mipushVo.getExtra().getUser_pic();
                int type = mipushVo.getExtra().getType();
                if (type == 100) {
                    Intent intent;
                    switch (ref_type) {
                        case "二手设备列表":
                            intent = new Intent(this, UsedSecondhandTypeActivity.class);
                            startActivity(intent);
                            break;
                        case "二手设备详情":
                            intent = new Intent(this, UsedMachineDetailActivity.class);
                            intent.putExtra("id", ref_id);
                            startActivity(intent);
                            break;
                        case "出租找活列表":
                            intent = new Intent(this, RentMachineNewActivity.class);
                            startActivity(intent);
                            break;
                        case "出租找活详情":
                            intent = new Intent(this, RentDetailActivity.class);
                            intent.putExtra("id", ref_id);
                            startActivity(intent);
                            break;
                        case "维修妙招列表":
                            intent = new Intent(this, IndurstryInformationActivity.class);
                            startActivity(intent);
                            break;
                        case "维修妙招详情":
                            intent = new Intent(this, IndustryInfoDetailActivity.class);
                            intent.putExtra("id", ref_id);
                            startActivity(intent);
                            break;
                        case "上门服务列表":
                            intent = new Intent(this, HomeServiceActivity.class);
                            startActivity(intent);
                            break;
                        case "上门服务详情":
                            intent = new Intent(this, HomeServiceDetailActivity.class);
                            intent.putExtra("id", ref_id);
                            startActivity(intent);
                            break;
                        case "工程师列表":
                            intent = new Intent(this, EngineerListActivity.class);
                            startActivity(intent);
                            break;
                        case "工程师详情":
                            intent = new Intent(this, EngineerDetailActivity.class);
                            intent.putExtra("id", ref_id);
                            startActivity(intent);
                            break;
                        case "商城列表":
                            NewWebActivity.start(this, "http://shop.jg969.com:90/client/index", "找配件", 1);
                            break;
                        case "商城详情":
                            NewWebActivity.start(this, ref_id, "商品详情", 0);//fengyi // bean.getShopDetailUrl()
                            break;
                    }
                } else if (type == 2) {
                    Intent intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                } else {
                    if (type == 7 && Util.isEmpty(ref_id)) {
                        Intent intent = new Intent(this, MainActivity.class);
                        startActivity(intent);
                    } else {

                        switch (ref_type) {
                            //二手机
                            case "0":
                                Intent intent0 = new Intent(this, UsedMachineDetailActivity.class);
                                intent0.putExtra("id", ref_id);
                                startActivity(intent0);
                                break;
                            //设备出租
                            case "1":
                                Intent intent1 = new Intent(this, RentDetailActivity.class);
                                intent1.putExtra("id", ref_id);
                                startActivity(intent1);
                                break;
                            //设备求租
                            case "2":
                                Intent intent2 = new Intent(this, QiuZuDetailActivity.class);
                                intent2.putExtra("id", ref_id);
                                startActivity(intent2);
                                break;
                            //问答
                            case "3":
                                FreeAskAnswerDetailActivity.startFreeAskAnswerDetailActivty( ref_id,this);
                                break;
                            case "4":
//                            int mtype;
//                            if (type == 5) {
//                                mtype = 2;
//                            } else if (type == 4) {
//                                //付费咨询结束提醒评价
//                            }
                                if (PreferencesUtil.getBoolean(this, PreferencesUtil.KEY_IS_ENGINEER)) {
                                    BiuEaseHelper
                                            .getInstance()
                                            .beginNewSingleChat(this
                                                    , "", huanxin_id
                                                    , toUserName
                                                    , pic, ref_id, 2, cid, 0);
                                } else {
                                    BiuEaseHelper
                                            .getInstance()
                                            .beginNewSingleChat(this
                                                    , "", huanxin_id
                                                    , toUserName
                                                    , pic, ref_id, 0, cid, 0);
                                }
                                break;
                            case "5":
                                Intent intent5 = new Intent(this, SystemPushActivity.class);
                                intent5.putExtra("type", 1);
                                intent5.putExtra("id", ref_id);
                                startActivity(intent5);

                                break;
                            case "6":
                                Intent intent6 = new Intent(this, SystemMessageActivity.class);
                                intent6.putExtra("type", type);
                                intent6.putExtra("id", ref_id);
                                startActivity(intent6);
                                break;
                        }
                    }
                }
            }
        } else {
            Log.i("xxxxxxxx", "body is null");
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.i("asktg", "onNewIntent");
        flag = intent.getIntExtra("flag", 0);
        if (flag == 123) {
            if (btn_consult != null & mViewPager != null) {
                if (PreferencesUtil.getBoolean(MainActivity.this, PreferencesUtil.KEY_IS_ENGINEER)) {
                    startActivity(new Intent(MainActivity.this, ConsultationActivity.class));
                } else {
                    btn_consult.setChecked(true);
                    mViewPager.setCurrentItem(1);
                }
            }
        } else if (flag == 222) {
            if (mViewPager != null) {
                mViewPager.setCurrentItem(2);
                btn_center.setChecked(true);
            }
        } else if (flag == 223) {
            if (mViewPager != null) {
                mViewPager.setCurrentItem(0);
                ben_home.setChecked(true);
            }
        }
        dialog = new TokenInvalidDialog(null, new TokenInvalidDialog.onResultCallBack() {
            @Override
            public void onSure() {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
        manager = getSupportFragmentManager();
        getPermissions();
        super.onNewIntent(intent);
    }


    private void getPermissions() {
        EasyPermissions.requestPermissions(this,
                "应用程序将要获取以下权限：内存读取权限,本地相册读取及手机状态权限",
                0,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA);

    }

    //    当权限被成功申请的时候执行回调，requestCode是代表你权限请求的识别码，list里面装着申请的权限的名字：
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        switch (requestCode) {
            case 0:
                MyApplication.getInstance().READ_PHONE_PERMISSION = true;
                break;
        }
    }

    //当权限申请失败的时候执行的回调
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        MyApplication.getInstance().READ_PHONE_PERMISSION = false;
        new AppSettingsDialog
                .Builder(this)
                .setRationale("您未授予程序相关权限，可能会导致部分功能无法正常使用，是否打开设置进行授权")
                .setPositiveButton("好")
                .build()
                .show();
//        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
////            Toast.makeText(this,"已拒绝权限" + sb + "并不再询问",Toast.LENGTH_SHORT);
//
//        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    private void initView() {
        flag = getIntent().getIntExtra("flag", 0);
        HasNew = (ImageView) findViewById(R.id.iv_has_new);
        ivMyShop = (ImageView) findViewById(R.id.ivMyShop);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mAppBarLayout = (AppBarLayout) findViewById(R.id.layout_app_bar);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        title = (TextView) findViewById(R.id.toolbar_title);
        mButtonGroup = (RadioGroup) findViewById(R.id.group);
        btn_consult = (RadioButton) findViewById(R.id.btn_consult);
        btn_center = (RadioButton) findViewById(R.id.btn_center);
        ben_home = (RadioButton) findViewById(R.id.ben_home);
        btnShopping = (RadioButton) findViewById(R.id.btnShopping);
        setSupportActionBar(mToolbar);
        mPagerAdapter = new myPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOffscreenPageLimit(5);
        getAppBarLayout().setVisibility(View.GONE);
        btnShopping.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                btnShopping.setChecked(false);
            }
        });
        btnShopping.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Information info = new Information();
                info.setAppkey("9d6b46705cd648b9bf1b66be4a9438bf");  //分配给App的的密钥
                if (!Util.isEmpty(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID))) {
                    info.setUid(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID));
                    //用户昵称，选填
//                    info.setUname(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.KEY_NAME));
//                    info.setRealname(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.KEY_NAME));
                    //用户电话，选填
                    info.setTel(PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.KEY_PHONE));
                }
                SobotApi.startSobotChat(getBaseContext(), info);
                return true;
            }
        });
        mButtonGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                int position = group.indexOfChild(group.findViewById(checkedId));
                switch (position) {
                    case 0:
                        setToolBarTitle("");
                        getAppBarLayout().setVisibility(View.GONE);
                        index = 0;
                        break;
//                    case 1:
//                        setToolBarTitle("");
//                        getAppBarLayout().setVisibility(View.GONE);
//                        break;
                    case 1:
                        index = 1;
                        setToolBarTitle("");
                        getAppBarLayout().setVisibility(View.GONE);
                        checkIsLogin();

                        break;
                    case 2:

                        break;
                    case 3:

//                        NewWebActivity.start(MainActivity.this, "http://shop.jg969.com:90/client/index", "找配件");
//                        setToolBarTitle("购物车");
                        getAppBarLayout().setVisibility(View.GONE);
                        checkIsLogin();
//                        mViewPager.setCurrentItem(index);
                        WebEvent.postEvent("", false);
                        break;
                    case 4:
                        index = 4;
                        setToolBarTitle("个人中心");
                        getAppBarLayout().setVisibility(View.VISIBLE);
                        checkIsLogin();
                        PersonalCenterEvent.postEvent(1);
                        break;
                    default:


                }
                mViewPager.setCurrentItem(position);
            }
        });

        //// TODO: 2018/3/29 考虑实际需求

        if (MyApplication.userIdIsEmpty(this))
            return;
        EMMessageListener messageListener = new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> list) {
                for (EMMessage message : list) {
                    EMLog.d("main", "onMessageReceived id : " + message.getMsgId());
                    // in background, do not refresh UI, notify it in notification bar
//                  iif(!easeUI.hasForegroundActivies()){
//                    if (Utils.isForeground(MainActivity.this, MainActivity.this.getComponentName().getClassName()))
                    if (message.getTo().equals(PreferencesUtil.getString(MainActivity.this, PreferencesUtil.KEY_HX_ID)) || message.getTo().equals(PreferencesUtil.getString(MainActivity.this, PreferencesUtil.KEY_PHONE))) {

                    }
                    EngineerPassEvent.postEvent(true);
                    if (PreferencesUtil.getBoolean(MainActivity.this, PreferencesUtil.KEY_IS_ENGINEER)) {
                        if (Utils.isForeground(MainActivity.this, "com.asktgapp.user.activity.ConsultationActivity") || Utils.isForeground(MainActivity.this, "com.asktgapp.user.activity.ChatActivity")) {
                            BiuEaseHelper.getInstance().getNotifier().play(message);
                        } else {

                            BiuEaseHelper.getInstance().getNotifier().notify(message);
                        }
                        HasNewEvent.postEvent(6);
                    } else {
                        if ((mButtonGroup.getCheckedRadioButtonId() == R.id.btn_consult && Utils.isForeground(MainActivity.this, MainActivity.this.getComponentName().getClassName())) || Utils.isForeground(MainActivity.this, "com.asktgapp.user.activity.ChatActivity")) {
                            BiuEaseHelper.getInstance().getNotifier().play(message);
                        } else {
                            BiuEaseHelper.getInstance().getNotifier().notify(message);
//                            EaseUI.getInstance().getNotifier().vibrateAndPlayTone(message);
                        }
                        HasNewEvent.postEvent(1);
                    }
                }
//                }
                notReadMessageNum();
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> list) {

            }

            @Override
            public void onMessageRead(List<EMMessage> list) {

            }

            @Override
            public void onMessageDelivered(List<EMMessage> list) {

            }

            @Override
            public void onMessageRecalled(List<EMMessage> list) {

            }

            @Override
            public void onMessageChanged(EMMessage emMessage, Object o) {

            }
        };
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        if (flag == 123) {
            if (PreferencesUtil.getBoolean(MainActivity.this, PreferencesUtil.KEY_IS_ENGINEER)) {
                startActivity(new Intent(MainActivity.this, ConsultationActivity.class));
            } else {
                btn_consult.setChecked(true);
                mViewPager.setCurrentItem(1);
            }
        }
        EMClient.getInstance().addConnectionListener(connectionListener);
    }

    //环信
    EMConnectionListener connectionListener = new EMConnectionListener() {
        @Override
        public void onConnected() {
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    doDisconnected(error);
                }
            });


        }
    };

    public void doDisconnected(int error) {
        Utils.onHxError(error);
        if (error == EMError.USER_REMOVED || error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
//            Toast.makeText(this, "帐号已经被移除", Toast.LENGTH_SHORT).show();
            PreferencesUtil.putString(MainActivity.this, PreferencesUtil.USER_ID, "");
            PreferencesUtil.putString(MainActivity.this, PreferencesUtil.KEY_HX_ID, "");
            BiuEaseHelper.loginOut();
            if (MyApplication.isNotFront) {
                MyApplication.getInstance().removeALLActivity();
            } else {
                try {
                    dialog.show(manager, "TokenInvalidDialog");
                } catch (Exception e) {
                    if (MyApplication.isNotFront) {
                        MyApplication.getInstance().removeALLActivity();
                    } else {
                        Toast.makeText(this, "登录失效", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }
                }

            }


        } else if (error == EMError.SERVER_SERVICE_RESTRICTED) {
//            Toast.makeText(this, "帐号已经被禁", Toast.LENGTH_SHORT).show();
//            finish();
        } else {

            BiuEaseHelper.reset();
        }
    }

    /**
     * 设置标题
     *
     * @param titleString
     */
    public void setToolBarTitle(String titleString) {
        if (title == null)
            title = (TextView) findViewById(R.id.toolbar_title);
        title.setText(titleString);
    }

    public AppBarLayout getAppBarLayout() {
        return mAppBarLayout;
    }

    public class myPagerAdapter extends FragmentPagerAdapter {

        public myPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            switch (position) {
                case 0://首页
                    return new NewNewHomeFragment();
//                    return new HomeFragment();
//                case 1://发布
//                    return new PublishFragment();
                case 1://咨询
                    if (PreferencesUtil.getBoolean(MainActivity.this, PreferencesUtil.KEY_IS_ENGINEER))
                        return new ConsultNewFragment();
                    else
                        return new PayConsultFragment();

                case 3://zhaopeijian

                    return new ShopWebViewFragment();
                case 4://个人中心

                    return new NewPersonalCenterFragment();

            }
            return new NewNewHomeFragment();
        }

        @Override
        public int getCount() {
            return 5;
        }

    }

    public void checkIsLogin() {
        if (MyApplication.userIdIsEmpty(this)) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.putExtra("reload", 1);
            startActivity(intent);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mViewPager.getCurrentItem() == 2) {
                WebEvent.postEvent("", true);
                return false;
            }
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
//        if (EventBus.getDefault().isRegistered(this)) {
        EventBus.getDefault().unregister(this);
//        }
//        unregisterReceiver(onePixelReceiver);
        super.onDestroy();
    }

    private ImageView englneerHasNew, userHasNew;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void hasNewMsg(HasNewEvent event) {
        if (userHasNew == null) {
            userHasNew = (ImageView) findViewById(R.id.iv_has_new);
        }
        if (englneerHasNew == null) {
            englneerHasNew = (ImageView) findViewById(R.id.iv_has_new2);
        }

        if (event.getType() == 1) {
            userHasNew.setVisibility(View.VISIBLE);
            showBubble(1);
        } else if (event.getType() == 0) {
            userHasNew.setVisibility(View.GONE);
            showBubble(0);
        } else if (event.getType() == 2) {
            if (btn_consult != null && mViewPager != null) {
                btn_consult.setChecked(true);
                mViewPager.setCurrentItem(1);
            }
        } else if (event.getType() == 3) {
            ImageView myNew = (ImageView) findViewById(R.id.iv_my_new);
            myNew.setVisibility(View.GONE);
            showBubble(0);
        } else if (event.getType() == 4) {
            ImageView myNew = (ImageView) findViewById(R.id.iv_my_new);
            myNew.setVisibility(View.VISIBLE);
            showBubble(1);

        } else if (event.getType() == 5) {
            englneerHasNew.setVisibility(View.GONE);
        } else if (event.getType() == 6) {
            englneerHasNew.setVisibility(View.VISIBLE);
        } else if (event.getType() == 900) {
//            if (SobotApi.getUnreadMsg(MyApplication.getInstance(), PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID)) > 0) {
//                ivMyShop.setVisibility(View.VISIBLE); //购物车小红点 可更改为客服小红点
//            } else {
//                ivMyShop.setVisibility(View.GONE);
//            }
        }

    }

    private void showBubble(int num) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
        Notification n = builder.build();
//        int defaults = Notification.DEFAULT_LIGHTS;
//        defaults |= Notification.DEFAULT_SOUND;
//        n.defaults = defaults;
        n.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL;
        DifferentNotifications.showBubble(getBaseContext(), n, 1801, num);
    }

    //消息接口
    private void notReadMessageNum() {

        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userId", PreferencesUtil.getString(this, PreferencesUtil.USER_ID));
//        params.put("platform", "0");
//        params.put("deviceId", Utils.getDeviceId(MyApplication.getInstance()));
        params.put("page", 1);
        Call<ApiResponseBody<DifferentTypeVO>> call = apiservice.notReadMessageNum(params);
        call.enqueue(new Callback<ApiResponseBody<DifferentTypeVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<DifferentTypeVO>> call, Response<ApiResponseBody<DifferentTypeVO>> response) {
                if (response.isSuccessful()) {
                    DifferentTypeVO bean = response.body().getResult();
                    if (bean != null) {
                        ImageView myNew = (ImageView) findViewById(R.id.iv_my_new);
                        if (bean.getNotReadNum() > 0) {
                            myNew.setVisibility(View.VISIBLE);
                            showBubble(bean.getNotReadNum());
                        } else {
                            showBubble(0);
                            myNew.setVisibility(View.GONE);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<DifferentTypeVO>> call, Throwable t) {
                showBubble(1);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
//        notReadMessageNum();
        Log.e(TAG, "onResume");
        MobclickAgent.onResume(this);
//        if (SobotApi.getUnreadMsg(MyApplication.getInstance(), PreferencesUtil.getString(MyApplication.getInstance(), PreferencesUtil.USER_ID)) > 0) {
//            ivMyShop.setVisibility(View.VISIBLE);//购物车小红点 可更改为客服小红点
//        } else {
//            ivMyShop.setVisibility(View.GONE);
////            showBubble(0);
//        }
        WebEvent.postEvent("1", true);
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e(TAG, "onPause");
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e(TAG, "onStart");
    }


    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG, "onStop");
    }

    private String TAG = "onePixelActivity";
}
